<template>
  <a-modal v-model:visible="visible" :title="isEdit ? '修改物料' : '新增物料'" @ok="handleOk" @cancel="handleCancel"
    :confirmLoading="confirmLoading" destroyOnClose>
    <a-form ref="formRef" :model="formData" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
      <a-form-item label="商品名称" name="name" required>
        <a-select v-model:value="formData.name" placeholder="请输入商品名称搜索" show-search :filter-option="false"
          :show-arrow="false" :not-found-content="null" @search="handleSearch" @change="handleSelect">
          <a-select-option v-for="item in productOptions" :key="item.id" :value="item.name">
            {{ item.name }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="输入单位" name="unit" required>
        <a-input v-model:value="formData.unit" placeholder="请输入单位" :maxlength="100" />
      </a-form-item>
      <a-form-item label="输入数量" name="quantity" required>
        <a-input-number v-model:value="formData.quantity" :min="0" placeholder="请输入数量" style="width: 100%" />
      </a-form-item>
      <a-form-item label="采购价格" name="purchasingPrice" required>
        <a-input-number v-model:value="formData.purchasingPrice" :min="0" placeholder="请输入采购价格" style="width: 100%" />
      </a-form-item>
      <a-form-item label="输入备注" name="remark">
        <a-textarea v-model:value="formData.remark" show-count allow-clear placeholder="请输入备注" :rows="2"
          :maxlength="500"></a-textarea>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import { defineComponent, ref, reactive } from 'vue';
import type { FormInstance } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import { bomProductApi } from '/@/api/base-data/product/bom-product';

/**
 * @description: 新增物料弹窗
 */

interface ProductOption {
  id: string;
  name: string;
  code: string;
  unit: string;
  price: number;
  skuCode: string;
}

export default defineComponent({
  name: 'AddMaterial',
  emits: ['confirm', 'refresh'],
  setup(props, { emit }) {
    const visible = ref(false);
    const confirmLoading = ref(false);
    const formRef = ref<FormInstance>();
    const isEdit = ref(false);
    const editId = ref<string | null>(null);
    const formData = reactive({
      goodsId: '',
      name: "",
      unit: '',
      quantity: '',
      purchasingPrice: '',
      remark: '',
      productId: '',
    });
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请选择商品' },
        { max: 100, message: '最大长度为100个字符' }
      ],
      unit: [
        { required: true, message: '请输入单位' },
        { max: 100, message: '最大长度为100个字符' }
      ],
      quantity: [{ required: true, message: '请输入数量' }],
      purchasingPrice: [{ required: true, message: '请输入采购价格' }],
      remark: [
        { required: false, message: '请输入备注' },
        { max: 100, message: '最大长度为100个字符' }
      ],
    };

    // 商品选项
    const productOptions = ref<ProductOption[]>([]);
    // 搜索商品
    const handleSearch = async (value: string) => {
      try {
        const params = {
          pageIndex: 1,
          pageSize: 10,
          name: value || ""
        };
        const response = await bomProductApi.query(params);
        if (response && response.datas) {
          productOptions.value = response.datas.map(item => ({
            id: item.id,
            name: item.name,
            code: item.code,
            unit: item.unit,
            price: item.price,
            skuCode: item.skuCode
          }));
          productOptions.value = productOptions.value.filter(item => item.id !== formData.productId);
        }
      } catch (error) {
        console.error('Search products error:', error);
        message.error('搜索商品失败');
        productOptions.value = [];
      }
    };
    // 选择商品，并将商品信息赋值给表单
    const handleSelect = (value: string) => {
      const selectedProduct = productOptions.value.find(item => item.name === value);
      console.log(selectedProduct)
      editId.value = selectedProduct?.id || null;
      if (selectedProduct) {
        formData.goodsId = selectedProduct.id;
        formData.unit = selectedProduct.unit;
        formData.purchasingPrice = selectedProduct.price.toString();
        formData.quantity = selectedProduct.quantity;
        formData.remark = selectedProduct.remark;
      }
    };
    // 初始化商品选项
    const initProductOptions = () => {
      handleSearch('');
    };
    // 新增或修改，提交弹框
    const handleOk = async () => {
      try {
        await formRef.value?.validate();
        confirmLoading.value = true;
        console.log("=============>formData", formData)
        // formData = formData.map(item => ({
        //   productId: editId.value,
        // }));
        const apiCall = isEdit.value
          ? bomProductApi.updateMaterial({ ...formData, id: editId.value })
          : bomProductApi.addMaterial(formData);

        await apiCall;
        message.success(isEdit.value ? '修改成功' : '添加成功');
        emit('refresh');
        handleCancel();
      } catch (error) {
        console.error('提交失败:', error);
        message.error('提交失败，请检查输入或稍后重试');
      } finally {
        confirmLoading.value = false;
      }
    };
    // 关闭新增弹窗
    const handleCancel = () => {
      visible.value = false;
      formRef.value?.resetFields();
      isEdit.value = false;
      editId.value = null;
      Object.assign(formData, {
        goodsId: '',
        name: '',
        unit: '',
        quantity: '',
        purchasingPrice: '',
        remark: '',
        productId: '',
      });
    };
    // 打开新增调用函数,主商品id===productId
    const openDialog = (id?: string, record?: any) => {
      visible.value = true;
      initProductOptions();
      console.log("=============>物料id", record)
      if (record) {
        console.log("=============>物料qwqweqwdeqwdqwdweid", record)
        isEdit.value = true;
        editId.value = record.id;
        Object.assign(formData, {
          goodsId: record.goodsId,
          name: record.name,
          unit: record.unit,
          quantity: record.quantity,
          purchasingPrice: record.purchasingPrice,
          remark: record.remark,
          productId: record.productId,
        });
      } else {
        isEdit.value = false;
        editId.value = null;
        Object.assign(formData, {
          goodsId: '',
          name: '',
          unit: '',
          quantity: '',
          purchasingPrice: '',
          remark: '',
          productId: id,
        });
      }
    };

    return {
      visible,
      confirmLoading,
      productOptions,
      handleSearch,
      handleSelect,
      formRef,
      formData,
      rules,
      handleOk,
      handleCancel,
      openDialog,
      isEdit,
      initProductOptions,
    };
  },
});
</script>
